﻿using System;
using System.Text;
using System.Windows.Forms;
using NATP2P.STUN;
using NATP2P.UDPNat;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace TestGui
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void txtSendMsg_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar==13)
            {
                ddd.Send(Encoding.ASCII.GetBytes(txtSendMsg.Text));
                txtSendMsg.Text = "";
            }
        }
      //  byte[] data=new byte[1024];
        EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
        UDPNatSocket ddd;
        EndPointMapRequest res;
        private void btnConnect_Click(object sender, EventArgs e)
        {
           //res = new EndPointMapRequest(int.Parse(txtIP.Text), "stun.stunprotocol.org");
            try
            {
                ddd = new UDPNatSocket(res, new IPEndPoint(IPAddress.Parse(txtRIP.Text), int.Parse(txtRP.Text)), (TypeNat) Enum.Parse( typeof(TypeNat),comboBox1.SelectedItem.ToString()));
                ddd.Connect();


                ddd.RaiseNewDatagramEvent += new EventHandler<NewDatagramEventArgs>(ddd_RaiseNewDatagramEvent);
                ddd.Receive();
               
            }
            catch (Exception ed)
            {

                MessageBox.Show(ed.Message);
            }
           
          
        }
       
        void ddd_RaiseNewDatagramEvent(object sender, NewDatagramEventArgs e)
        {
            listReceMsg.Items.Add(Encoding.ASCII.GetString(e.Data));
        }
        private void button1_Click(object sender, EventArgs e)
        {

            res = new EndPointMapRequest(int.Parse(txtIP.Text), "stun.stunprotocol.org");
            res.Send();
            txtEIP.Text = res.ExternalEndPoint.Address.ToString();
            txtEP.Text = res.ExternalEndPoint.Port.ToString();
           /* UdpClient udp = new UdpClient(int.Parse(txtIP.Text));
            byte[] data = Encoding.ASCII.GetBytes(txtIIP.Text);
            udp.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.168.1.2"), 8080));
            IPEndPoint ip = new IPEndPoint(IPAddress.Any,0);
            byte[] temp= udp.Receive(ref ip);
            txtRP.Text = Encoding.ASCII.GetString(temp);
            udp.Close();*/
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ddd = new UDPNatSocket(res, new IPEndPoint(IPAddress.Parse(txtRIP.Text), int.Parse(txtRP.Text)),(TypeNat) Enum.Parse( typeof(TypeNat),comboBox1.SelectedItem.ToString(), true ));
            ddd.Listen();


            ddd.RaiseNewDatagramEvent += new EventHandler<NewDatagramEventArgs>(ddd_RaiseNewDatagramEvent);
            ddd.Receive();
        }

       
    }
}
